#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<cstring>
#include<cstdio>

void ChildWrite(int wfd)
{
    //char buffer[1024];
    //int cnt = 0;
    char c = 0;
    int cnt = 0;
    while(true)
    {
        //snprintf(buffer, sizeof(buffer), "I am child, pid: %d, cnt: %d", getpid(), cnt++);
        write(wfd, &c, 1);
        printf("child:%d\n", cnt++);
        //sleep(2);//1写慢读快
        break;
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        buffer[0] = 0;
        // // 从管道读取数据（阻塞式调用）
        //子进程每 1 秒写一次，父进程等子进程写完就立刻读，二者因管道的阻塞特性 “间接同步”，表现为每秒刷新一次数据
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say: " << buffer << std::endl;
            //sleep(2);//2写快读慢
            //3写关读快
        }
        else if(n == 0)//子进程结束
        {
            std::cout << "n: " << n << std::endl;
            //std::cout << "child退出，我也退出";
            //break;
        }
        else
        {
            break;
        }

        break;
    }
}




int main() 
{
    //1.创建管道
    int fds[2] ={0};
    int n = pipe(fds);
    if(n < 0)
    {
        std::cout << "pipe error" << std::endl;
        return -1;
    }
    std::cout << "fds[0]: " << fds[0] << std:: endl;
    std::cout << "fds[1]: " << fds[1] << std:: endl;

    //2.父进程写入数据创建子进程
    pid_t id = fork();
    if(id ==0)
    {
        //child
        //3.关闭子进程读端
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //3.父进程关闭写端
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    //waitpid(id, nullptr, 0);
    

    sleep(5);

    int status = 0;
    int ret = waitpid(id, &status, 0); // 获取到子进程的退出信息吗！！！
    if(ret > 0)
    {
        printf("exit code: %d, exit signal: %d\n", (status>>8)&0xFF, status&0x7F);
        sleep(5);
    }
    return 0;
}